<template>
    <div class="sys-log-container flex flex-col">
        <a-card class="mb-2.5">
            <common-form
                :model="state.queryForm"
                name="log-form"
                @query="handleQuery"
                @reset="handleReset"
            >
                <a-form-item
                    label="开始时间"
                    name="startTime"
                    class="w-1/3"
                >
                    <a-date-picker
                        v-model:value="state.queryForm.startTime"
                        format="YYYY-MM-DD HH:mm:ss"
                        show-time
                        :show-time-options="{ format: 'HH:mm:ss' }"
                        placeholder="请选择开始时间"
                    />
                </a-form-item>
                <a-form-item
                    label="结束时间"
                    name="endTime"
                    class="w-1/3"
                >
                    <a-date-picker
                        v-model:value="state.queryForm.endTime"
                        format="YYYY-MM-DD HH:mm:ss"
                        show-time
                        :show-time-options="{ format: 'HH:mm:ss' }"
                        placeholder="请选择结束时间"
                    />
                </a-form-item>
            </common-form>
        </a-card>
        <a-card class="flex-1 card-table">
            <common-table 
                :columns="columns"
                :data="state.tableData"
                :pagination="state.pagination"
                :loading="state.loading"
                @change="handleTableChange"
            >
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'status'">
                        <a-tag color="green" v-if="record.status === 'Success'">成功</a-tag>
                        <a-tag color="red" v-if="record.status === 'Error'">失败</a-tag>
                        <a-tag color="orange" v-else>{{ record.status }}</a-tag>
                    </template>
                    <template v-if="column.dataIndex === 'logLevel'">
                        <a-tag color="red" v-if="record.logLevel === 'Error'">错误</a-tag>
                        <a-tag color="orange" v-if="record.logLevel === 'Warn'">警告</a-tag>
                        <a-tag color="blue" v-if="record.logLevel === 'Info'">信息</a-tag>
                        <a-tag color="purple" v-if="record.logLevel === 'Debug'">调试</a-tag>
                    </template>
                    <template v-if="column.dataIndex === 'elapsed'">
                        {{ record.elapsed }} ms
                    </template>
                </template>
            </common-table>
        </a-card>
    </div>
</template>

<script setup lang="ts" name="sysVisLog">
import { onMounted, reactive, ref } from 'vue';
import CommonForm from '@/components/common-form/index.vue';
import CommonTable from '@/components/common-table/index.vue';
import type { ResType } from '@/api/types';
import { GetLogVisPage } from '@/api/sys/syslog';
import { showMsg } from '@/utils';
import { DatePicker } from 'ant-design-vue';
import type { TableParamsResType } from '../../onlineUser/type';

defineOptions({
    name:"sysVisLog"
})

const state = reactive({
    queryForm: {
        startTime: null as Date | null,
        endTime: null as Date | null
    },
    tableData: [] as any[],
    loading: false,
    pagination: {
        page: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条记录`
    }
});

const columns = [
    { title: '序号', dataIndex: 'index', key: 'index', width: 60, align: 'center', customRender: ({ index }) => index + 1 },
    { title: '日志时间', dataIndex: 'logDateTime', key: 'logDateTime', width: 180, align: 'center' },
    { title: '模块名称', dataIndex: 'controllerName', key: 'controllerName', width: 120 },
    { title: '方法名称', dataIndex: 'actionName', key: 'actionName', width: 120 },
    { title: '显示名称', dataIndex: 'displayTitle', key: 'displayTitle', width: 150 },
    { title: '执行状态', dataIndex: 'status', key: 'status', width: 90, align: 'center' },
    { title: '日志级别', dataIndex: 'logLevel', key: 'logLevel', width: 90, align: 'center' },
    { title: '账号', dataIndex: 'account', key: 'account', width: 100 },
    { title: '真实姓名', dataIndex: 'realName', key: 'realName', width: 100 },
    { title: 'IP地址', dataIndex: 'remoteIp', key: 'remoteIp', width: 130 },
    { title: '登录地点', dataIndex: 'location', key: 'location', width: 120 },
    { title: '浏览器', dataIndex: 'browser', key: 'browser', width: 150 },
    { title: '操作系统', dataIndex: 'os', key: 'os', width: 120 },
    { title: '操作用时', dataIndex: 'elapsed', key: 'elapsed', width: 90, align: 'center' }
];

const handleQuery = async () => {
    state.loading = true;
    try {
        // 调用API获取日志数据，传入分页参数和日期范围
        const res = await GetLogVisPage({
            page: state.pagination.page,
            pageSize: state.pagination.pageSize,
            ...state.queryForm
        }) as ResType<TableParamsResType<any>>;

        if (res.data.code == 200) {
            state.tableData = res.data.result.items;
            state.pagination.total = res.data.result.total;
        } else {
            showMsg(res.data.message || '获取日志数据失败', 'error');
        }
    } catch (error) {
        showMsg('获取日志数据异常', 'error');
        console.error('获取日志数据异常:', error);
    } finally {
        state.loading = false;
    }
};

const handleReset = () => {
    state.queryForm.startTime = null;
    state.queryForm.endTime = null;
    state.pagination.page = 1;
    handleQuery();
};

const handleTableChange = (pagination: any) => {
    state.pagination.page = pagination.current;
    state.pagination.pageSize = pagination.pageSize;
    handleQuery();
};

// 日期格式化辅助函数
const formatDate = (date: Date): string => {
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
};

onMounted(() => {
    handleQuery();
});
</script>

<style lang="scss" scoped>
.sys-log-container {
    .card-table {
        :deep(.ant-card-body) {
            height: 100%;
            padding: 16px;
        }
    }
}

:deep(.ant-form-item) {
    margin-bottom: 16px;
}
</style>